package com.trkj.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.trkj.dao.EmpDAO;
import com.trkj.pojo.Emp;
import com.trkj.pojo.Loan;
import com.trkj.pojo.Loanlog;
import com.trkj.service.LoanService;
import com.trkj.service.WorkFlowService;
import com.trkj.vo.LoanEmpVo;

@Controller
@SessionAttributes({"emp", "funcIds"})
public class LoanController {
	@Autowired
	LoanService loanService;
	@Autowired
	WorkFlowService workFlowService;
	
	@Autowired
	EmpDAO empDAO;
	
	/**
	 * 调用个人借款主界面
	 * @author csj
	 * @return
	 */
	@GetMapping("/PersonalLoan")
	public String PersonalLoan() {
		return "PersonalLoan";
	}
	
	/**
	 * 带条件查询员工借款的所有信息
	 * @author csj
	 * @param empName
	 * @param deptName
	 * csj
	 * @return
	 */
	@RequestMapping("loanEmpInfo")
	@ResponseBody
	public List<Map<String, Object>> loanEmpInfo(String empName,String deptName) {
		return loanService.checkempLoanInfo(empName, deptName);
	}
	/**
	 * 暂存一个借款申请
	 * @author Lixd
	 * @param loan
	 * @param empId
	 * @param deptId
	 * @return
	 */
	@RequestMapping("/save_loan")
	@ResponseBody
	public boolean save_loan(Loan loan,Integer empId,Integer deptId) {
		Integer save_loan = loanService.save_loan(loan, empId, deptId);
		if (save_loan!=0) {
			return true;
		}
		return false;
	}
	/**
	 * 得到自动填入的emp的信息
	 * @author Lixd
	 * @param emp
	 * @return
	 */
	@RequestMapping("/getEmpInfo")
	@ResponseBody
	public Map<String, Object> getEmpInfo(Model model) {
		Emp emp = (Emp)model.asMap().get("emp");
		return loanService.getEmpInfo(emp.getEmpId());
	}
	/**
	 * 借款部署流程接口
	 * @author Lixd
	 */
	@RequestMapping("/bushu_loan")
	public void deploymentProcessDefinition_classpath() {
		workFlowService.deploymentProcessDefinition_classpath("人员借款流程",
				"diagrams/loan_actProcess.png","diagrams/loan_actProcess.bpmn");
	}
	/**
	 * 借款流程提交
	 * @author Lixd
	 * @param employ
	 * @param deptId
	 * @param positionId
	 * @param processDefinitionKey
	 * @return
	 */
	@RequestMapping("/submit_loan")
	@ResponseBody
	public boolean submit_loan(Model model,Loan loan,Integer empId,Integer deptId,@RequestParam("pk")String processDefinitionKey) {
		Integer useid = getOnLineEmp(model);
		Integer processId = loanService.save_loan(loan, empId, deptId);
		if (processId!=0) {
			return workFlowService.startEmployProcess(processId, useid, processDefinitionKey);
		}
		return false;
	}
	/**
	 * 获取登录人的id
	 * @author Lixd
	 * @param model
	 * @return
	 */
	private Integer getOnLineEmp(Model model) {
		Emp emp = (Emp)model.asMap().get("emp");
		Integer useid = emp.getEmpId();
		return useid;
	}
	
	/**
	 * 调用编辑借款记录界面
	 * @author csj
	 * @return
	 */
	@GetMapping("/editLoan")
	public String editLoan() {
		return "editLoan";
	}
	
	/**
	 * 获取编辑所需要的借款信息
	 * @author csj
	 * @param empId
	 * @return
	 */
	@RequestMapping("/editloanInfo")
	public @ResponseBody LoanEmpVo editloanInfo(@RequestParam("empId") Integer empId) {
		return loanService.editLoan(empId);
	}
	
	/**
	 * 保存借款记录
	 * @author csj
	 * @param loanlog
	 * @param empId
	 * @return
	 */
	@RequestMapping("/saveloanInfo")
	public @ResponseBody boolean saveloanInfo(Loanlog loanlog,
			@RequestParam("empId") Integer empId){
		
		 Integer info = loanService.saveLoanInfo(loanlog, empId);
		 if (info!=0) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
	 * 调用借款记录界面
	 * @author csj
	 * @return
	 */
	@GetMapping("/loanlogInfo")
	public String loanlogInfo() {
		return "loanlogInfo";
	}
	
	/**
	 * 带条件的借款记录查询
	 * @author csj
	 * @param empId
	 * @param onetime
	 * @param lasttime
	 * @return
	 */
	@RequestMapping("/loanlogempInfo")
	public @ResponseBody List<LoanEmpVo> loanlogempInfo(@RequestParam("empId") Integer empId,
			Date onetime,
			Date lasttime) {
		System.out.println(onetime);
		System.out.println(lasttime);
		List<LoanEmpVo> list = loanService.loanlogInfo(empId, onetime, lasttime);
		return list;
	}
	
	/**
	 * 个人借款信息导出
	 * @author csj
	 * @param response
	 * @param httpSession
	 * @param deptName
	 * @param empName
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/loanlogDaohu.xls",method = RequestMethod.GET)  
    @ResponseBody
    public void loanlogDaohu(HttpServletResponse response,HttpSession httpSession,String deptName ,String empName) throws UnsupportedEncodingException{  
        //一、从后台拿数据  
          //得到session中的id数字
			//OaEmpform oaEmpform = (OaEmpform) httpSession.getAttribute("empdx");
			//String oaEmpid = oaEmpform.getOaEmpid();
		List<Object[]> list=null;	
		if(empName!=null&&deptName!=null) {
			list = empDAO.findemploanANDtiaojian(empName+"%",deptName+"%");
		}else if (empName!=null||deptName!=null) {
			list = empDAO.findemploanORtiaojian(empName+"%",deptName+"%");
		}else {
			list = empDAO.findemploanInfo();
		}  
            //二、 数据转成excel  
            response.setCharacterEncoding("UTF-8");  
            response.setContentType("application/x-download");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String date= sf.format(new Date());
            String fileName = date+"借款信息表.xls";  
            fileName = URLEncoder.encode(fileName, "UTF-8");  
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);  
            // 第一步：定义一个新的工作簿  
            HSSFWorkbook wb = new HSSFWorkbook();  
            // 第二步：创建一个Sheet页  
            HSSFSheet sheet = wb.createSheet("startTimeendTime");  
            sheet.setDefaultRowHeight((short) (2 * 256));//设置行高  
            sheet.setColumnWidth(0, 4000);//设置列宽  
            sheet.setColumnWidth(1,5500);  
            sheet.setColumnWidth(2,5500);  
            sheet.setColumnWidth(3,5500);  
            sheet.setColumnWidth(4,5500);
            HSSFFont font = wb.createFont();  
            font.setFontName("宋体");  
            font.setFontHeightInPoints((short) 16);  
            HSSFRow row = sheet.createRow(0);  
            HSSFCell cell = row.createCell(0);  
            cell.setCellValue("");
            cell = row.createCell(1);
            cell.setCellValue("员工编号");
            cell = row.createCell(2);
            cell.setCellValue("部门名称");  
            cell = row.createCell(3);  
            cell.setCellValue("员工姓名");  
            cell = row.createCell(4);  
            cell.setCellValue("借款余额");  
            cell = row.createCell(5);  
            HSSFRow rows;  
            HSSFCell cells;  
            int i=1;
            for (Object[] objects : list) {
                // 第三步：在这个sheet页里创建一行  
                rows = sheet.createRow(i);  
                // 第四步：在该行创建一个单元格  
                cells = rows.createCell(0);  
                // 第五步：在该单元格里设置值  
                cells.setCellValue(i);  
                cells = rows.createCell(1); 
                cells.setCellValue(objects[0]+"");  
                cells = rows.createCell(2); 
                cells.setCellValue(objects[1]+"");  
                cells = rows.createCell(3);  
                cells.setCellValue(objects[2]+"");  
                cells = rows.createCell(4);  
                cells.setCellValue(objects[3]+"");  
                cells = rows.createCell(5);  
                i++;
            }  
                try {  
                    OutputStream out = response.getOutputStream();  
                    wb.write(out);  
                    out.close();  
                    wb.close();  
                } catch (IOException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
    }
	
}
